package work.dataformat;

import work.fram.JDBCConnect;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class IDCard {

    public static void main(String[] args) throws SQLException {

        Statement statement = JDBCConnect.getStatement();

        String regex = "^[1-9]\\d{5}(18|19|20|(3\\d))\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";

        Statement update = JDBCConnect.getStatement();

        //首先查出所有数据

        ResultSet query = statement.executeQuery("select idcard,sysid from tc_md_personnel");

        int i = 0;

        while (query.next()) {

            String idcard = query.getString("idcard");

            if (!idcard.matches(regex)) {

                String format = format(idcard);

                String sql = "update tc_md_personnel set idcard=\"" + format + "\" where sysid=\"" + query.getString("sysid") + "\"";

                try {
                   // System.out.println(sql);
                    update.execute(sql);
                } catch (Exception e) {
                    System.out.println(e);
                }

            }

        }

    }

    private static String format(String old) {
        char[] chars = old.toCharArray();

        StringBuilder builder = new StringBuilder();

        for (char aChar : chars) {
            if (allow(aChar)) {
                builder.append(aChar);
            }
        }

        return builder.toString();
    }

    private final static char[] allows = "0123456789xX".toCharArray();
    private static boolean allow(char c) {

        for (char ch : allows) {
            if (ch == c) {
                return true;
            }
        }

        return false;
    }

}
